package org.cook.utils.html.yyyy;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;

import org.cook.utils.common.Constants;
import org.cook.utils.common.FileUtils;
import org.cook.utils.common.Utils;
import org.cook.utils.extend.SortedList;
import org.htmlcleaner.CleanerProperties;
import org.htmlcleaner.HtmlCleaner;
import org.htmlcleaner.TagNode;

public class KeyworkFilterInFiles {
	
	private static final String htmlPrefix = "file:///Z:/shared/yueyang-hospital2/yymyc/www.yymyc.com/cn/zhjia/";
	
	private static final HtmlCleaner cleaner = new HtmlCleaner();
	public static final List<Doctor> matchedDoctors = new ArrayList<Doctor>();
	public static final List<String> northDoctorPinyinNames = new ArrayList<String>();
	public static final Map<String, String> allDoctorNameDeptMap = new HashMap<String, String>();
	
	/*
	 *      11  12  13   14  15  16  17
	 * 上午: 周一 周二 周三 周四 周五 周六 周日
	 *      21  22  23   24  25  26  27
	 * 下午: 周一 周二 周三 周四 周五 周六 周日
	 */
	private static final Map<Integer, List<Doctor>> scheduleMap = new HashMap<Integer, List<Doctor>>(4);
	
	
	public KeyworkFilterInFiles() {
		CleanerProperties props = cleaner.getProperties();
		props.setCharset(Constants.ENCODING_GB2312);
	}
	
	public static void main(String[] args) throws Exception {
		KeyworkFilterInFiles analyser = new KeyworkFilterInFiles();
		
		analyser.initNorthDoctorNames();
		analyser.initAllDoctorTitles();
		
		String baseDir = "/storage/shared/yueyang-hospital/yymyc/www.yymyc.com/cn/zhjia";
		File[] files = new File(baseDir).listFiles();
		
		CountDownLatch latch = new CountDownLatch(files.length);
		for (File f : files) {
			AnalyseThread th = new AnalyseThread(f, latch);
			th.start();
		}

		// /html/body/table[2]/tbody/tr[3]/td[2]
		
//		CountDownLatch latch = new CountDownLatch(1);
//		// qita_1.asp-page1=252.htm jtie_1.asp-page1=91.htm qita.asp-page=8.htm
//		AnalyseThread th = new AnalyseThread(new File(baseDir + "/qita_1.asp-page1=252.htm"), latch);
//		th.start();
		
		try {
			latch.await();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
		int workday = 0;
		for (Doctor doctor : matchedDoctors) {
			if (allDoctorNameDeptMap.containsKey(doctor.getPinyinName())) {// set dept
				doctor.setDept(allDoctorNameDeptMap.get(doctor.getPinyinName()));
			}
			workday = doctor.getWorkTimeDay();
			if (!scheduleMap.containsKey(workday)) {
				scheduleMap.put(workday, new SortedList<Doctor>());
			}
			scheduleMap.get(workday).add(doctor);
		}
		
//		System.out.println(analyser.toSchduleHtml());
		
		System.out.println(analyser.toHtml());
	}
	
	public void initNorthDoctorNames() throws Exception {
		String target = "/storage/shared/yueyang-hospital/yymyc/www.yymyc.com/cn/zhjia/ylb-1.htm";
		
		TagNode node = cleaner.clean(new File(target));
		TagNode[] bodyNodes = node.getElementsByName("body", false);
		
		for (TagNode body : bodyNodes) {
			Object[] northDoctors = body.evaluateXPath("//td[@class='style16']");
			String content = "";
			for (int i=0; i<northDoctors.length; i++) {
				content = ((TagNode) northDoctors[i]).getText().toString();
				northDoctorPinyinNames.add(Utils.stringToPinyin(Utils.replaceAll(content.substring(0, 3), "\\s+", "")));
			}
		}
	}
	
	public void initAllDoctorTitles() throws Exception {
		String target = "/storage/shared/yueyang-hospital/yymyc/www.yymyc.com/cn/zhjia/ylb-1.htm";
		
		TagNode node = cleaner.clean(new File(target));
		TagNode[] bodyNodes = node.getElementsByName("body", false);
		
		String content = "";
		for (TagNode body : bodyNodes) {
			Object[] allDoctors = body.evaluateXPath("//tr[@height='14']/td");
			
			for (int i=0; i<allDoctors.length; i++) {
				content = ((TagNode) allDoctors[i]).getText().toString().trim();
				content = Utils.replaceAll(content, "\\r+", "");
				content = Utils.replaceAll(content, "\\n+", "");
				if (content.length() > 5) {
					allDoctorNameDeptMap.put(Utils.stringToPinyin(Utils.replaceAll(content.substring(0, 3), "\\s+", "")), Utils.replaceAll(content.substring(3, content.length()), "\\s+", ""));
				}
			}
		}
	}
	
	@SuppressWarnings("unchecked")
	public String toSchduleHtml() throws Exception {
		String template =FileUtils.getFileContent(FileUtils.getResourcePath("schedule.html"));
		
		StringBuilder html = new StringBuilder();
		int rowspan1 = 0; int rowspan2 = 0; 
		// calculate max rows
		for (Integer wday : scheduleMap.keySet()) {
			List<Doctor> ds = scheduleMap.get(wday);
			if (wday > 10 && wday < 20) {
				if (ds.size() > rowspan1) rowspan1 = ds.size();
			} else if (wday > 20) {
				if (ds.size() > rowspan2) rowspan2 = ds.size();
			}
		}
		
		List<Doctor>[] ds1 = new List[]{scheduleMap.get(11), scheduleMap.get(12), scheduleMap.get(13), scheduleMap.get(14), scheduleMap.get(15), scheduleMap.get(16), scheduleMap.get(17)};
		List<Doctor>[] ds2 = new List[]{scheduleMap.get(21), scheduleMap.get(22), scheduleMap.get(23), scheduleMap.get(24), scheduleMap.get(25), scheduleMap.get(26), scheduleMap.get(27)};
		
		html.append(schduleDoctorToHtml(11, ds1)).append(Constants.NEW_LINE_UNIX).append(schduleDoctorToHtml(21, ds2));
		
		String content = template.replace("${content}", html.toString());
		
		return content;
	}
	
	private String schduleDoctorToHtml(int wday, List<Doctor>[] ds) {
		StringBuilder html = new StringBuilder();
		
		int rowspan = 0;
		// calculate max rows
		for (List<Doctor> d : ds) {
			if (wday > 10 && wday < 20) {
				if (Utils.isNotEmpty(d) && d.size() > rowspan) rowspan = d.size();
			} else if (wday > 20) {
				if (Utils.isNotEmpty(d) && d.size() > rowspan) rowspan = d.size();
			}
		}
		
		html.append("<tr>").append(Constants.NEW_LINE_UNIX);
		html.append("<td rowspan='").append(rowspan).append("' >").append("上午").append("</td>")
			.append(getDoctorTd(ds[0], 0)).append(getDoctorTd(ds[1], 0)).append(getDoctorTd(ds[2], 0)).append(getDoctorTd(ds[3], 0))
			.append(getDoctorTd(ds[4], 0)).append(getDoctorTd(ds[5], 0)).append(getDoctorTd(ds[6], 0)).append(Constants.NEW_LINE_UNIX);
		html.append("</tr>").append(Constants.NEW_LINE_UNIX);
		for (int i=1; i<rowspan; i++) {
			html.append("<tr>").append(Constants.NEW_LINE_UNIX);
			html.append(getDoctorTd(ds[0], i)).append(getDoctorTd(ds[1], i)).append(getDoctorTd(ds[2], i)).append(getDoctorTd(ds[3], i))
			    .append(getDoctorTd(ds[4], i)).append(getDoctorTd(ds[5], i)).append(getDoctorTd(ds[6], i)).append(Constants.NEW_LINE_UNIX);
			html.append("</tr>").append(Constants.NEW_LINE_UNIX);
		}
		
		return html.toString();
	}
	
	private String getDoctorTd(List<Doctor> ds, int index) {
		Doctor d = null;
		if (Utils.isNotEmpty(ds) && ds.size() > index) {
			d = ds.get(index);
		}
		
		StringBuilder td = new StringBuilder();
		
		td.append("<td").append(isDoctorAtNorth(d) ? " style='color: red'" : "").append(">").append(d != null ? d.getName() : "");
		if (d != null && d.getName().length() + d.getDept().length() < 8) {
			int spaceNum = 8 - d.getName().length() - d.getDept().length();
			for (int i=0; i<spaceNum; i++) {
				td.append("&nbsp;");
			}
		}
		td.append("</td>");
		return td.toString();
	}
	
	public boolean isDoctorAtNorth(Doctor d) {
		if (d == null) return false;
		return northDoctorPinyinNames.contains(d.getPinyinName());
	}
	
	public String toHtml() throws Exception {
		String template =FileUtils.getFileContent(FileUtils.getResourcePath("result.html"));
		
		StringBuilder content = new StringBuilder();
		for (Doctor doctor : matchedDoctors) {
			content.append(doctor.toText()).append(Constants.NEW_LINE_UNIX);
		}
		
		String html = template.replace("${content}", content.toString());
		
		return html;
	}
	
	
	
	
	
}



